<?php
declare (strict_types=1);

namespace app\admin\model\auth;

use app\admin\model\BaseModel;

class Admin extends BaseModel
{
    //当前模型对应的数据表名称
    protected $name = 'admin';

    public function getList($filter = []): array
    {
        $where = function ($query) use ($filter) {
            if (isset($filter['username'])) {
                $query->where('username', 'like', '%' . $filter['username'] . '%');
            }
            if (isset($filter['realname'])) {
                $query->where('realname', 'like', '%' . $filter['realname'] . '%');
            }
            if (isset($filter['status'])) {
                $query->where('status', '=', $filter['status']);
            }
        };
        $order = ['id' => 'asc'];
        return self::getPageList($where, $order);
    }

    public function setGroupAccess($group)
    {
        // 先移除所有权限
        $this->delGroupAccess();

        $dataList = [];
        foreach ($group as $value) {
            $dataList[] = ['uid' => $this->id, 'group_id' => $value];
        }
        $GroupAccessModel = new GroupAccess();
        $GroupAccessModel->saveAll($dataList);
    }

    public function delGroupAccess()
    {
        $GroupAccessModel = new GroupAccess();
        $GroupAccessModel->where('uid', '=', $this->id)->delete();
    }

    public function getLoginTimeAttr($value, $data)
    {
        if ($value) {
            return date('Y-m-d H:i:s', $value);
        } else {
            return '未登录';
        }
    }

}